package com.chris.design.pattern.samples.observer;

import java.util.ArrayList;
import java.util.List;

/**
 * 被观察者对象
 * @author Chris
 */
public abstract class AbstractSubject {

    /**
     * add or remove method, may be not thread-safe
     */
    List<Observer> observers = new ArrayList<>();

    /**
     * add element, not thread-safe
     * @param observer
     */
    public void attach(Observer observer) {
        observers.add(observer);
        System.out.println("attach an observer");
    }

    /**
     * remove element, not thread-safe
     * @param observer
     */
    public void detach(Observer observer) {
        observers.remove(observer);
        System.out.println("detach an observer");
    }

    public abstract void change(String newState, PushOrPullEnum type);

    /**
     * 通知所有注册的观察者对象. 推模式
     * @param newState
     */
    public void notifyObservers(String newState) {
        System.out.println("observer - push pattern");
        for (Observer o : observers) {
            o.update(newState);
        }
    }

    /**
     * 通知所有注册的观察者对象. 拉模式
     */
    public void notifyObservers() {
        System.out.println("observer - pull pattern");
        for (Observer o : observers) {
            o.update(this);
        }
    }
}
